package com.xunshangwang.pinhaohuo.ui.activities;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.xunshangwang.pinhaohuo.R;
import com.xunshangwang.pinhaohuo.entity.Goods;
import com.xunshangwang.pinhaohuo.entity.Group;
import com.xunshangwang.pinhaohuo.entity.Order;
import com.xunshangwang.pinhaohuo.entity.User;
import com.xunshangwang.pinhaohuo.http.HttpTool;
import com.xunshangwang.pinhaohuo.http.JsonHttpHandler;
import com.xunshangwang.pinhaohuo.tools.CommonTool;
import com.xunshangwang.pinhaohuo.transformation.CircleTransformation;
import com.xunshangwang.pinhaohuo.ui.dialogs.ShareDialog;
import com.xunshangwang.pinhaohuo.widgets.LoadLayout;
import com.xunshangwang.pinhaohuo.widgets.TimeTextView;

import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cz.msebera.android.httpclient.Header;
import tool.library.ToastTool;
import tool.library.adapter.BaseRecyclerAdapter;

/**
 * Created by xzp on 16/3/1.
 */
public class GroupDetailActivity extends BaseActivity implements View.OnClickListener{
    private NestedScrollView mRootView;
    private RecyclerView mRecycler;
    private ImageView mPlayIntroductionBtn;
    private LoadLayout mLoad;
    private Group mGroup;
    private TextView mGroupIdText,mGoodsNameText,mGoodsPriceText,mLeaderNameText;
    private ImageView mGoodsImage,mLeaderHeadImage;
    private TimeTextView mTimeText;
    private GroupUserAdapter mAdapter;
    private ImageView mStatusImage;
    private Button mFunctionBtn;
    private View mBottomBar;
    private boolean mIsJoin;
    private boolean mIsLogin;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_detail);
        mIsLogin=getMainApplication().isLogin();
        findView();
        initView();
        mRootView.post(new Runnable() {
            @Override
            public void run() {
                int rootHeight = mRootView.getMeasuredHeight();
                int otherHeight = findViewById(R.id.top_panel).getMeasuredHeight() + findViewById(R.id.goods_panel).getMeasuredHeight() +
                        mPlayIntroductionBtn.getMeasuredHeight() + 1;
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, rootHeight - otherHeight);
                mRecycler.setLayoutParams(params);
            }
        });
        requestGroupDetail();
    }
    private void findView(){
        mRootView= (NestedScrollView) this.findViewById(R.id.root_view);
        mRecycler= (RecyclerView) this.findViewById(R.id.group_person_list);
        mPlayIntroductionBtn= (ImageView) this.findViewById(R.id.play_introduction_btn);
        mLoad= (LoadLayout) this.findViewById(R.id.load_layout);
        mGroupIdText= (TextView) this.findViewById(R.id.group_id_text);
        mGoodsNameText= (TextView) this.findViewById(R.id.goods_name_text);
        mGoodsPriceText= (TextView) this.findViewById(R.id.goods_price_text);
        mLeaderNameText= (TextView) this.findViewById(R.id.group_leader_name_text);
        mGoodsImage= (ImageView) this.findViewById(R.id.goods_image);
        mLeaderHeadImage= (ImageView) this.findViewById(R.id.group_leader_head_image);
        mTimeText= (TimeTextView) this.findViewById(R.id.group_last_time_text);
        mStatusImage= (ImageView) this.findViewById(R.id.group_status_image);
        mFunctionBtn= (Button) this.findViewById(R.id.group_function_btn);
        mBottomBar=this.findViewById(R.id.detail_bottom_bar);
    }
    private void initView(){
        mRecycler.setLayoutManager(new LinearLayoutManager(this));
        mRecycler.addItemDecoration(new UserItemDecoration());
        TextView shopBtn= (TextView) findViewById(R.id.shop_btn);
        shopBtn.setOnClickListener(this);
        Drawable drawable=ContextCompat.getDrawable(this,R.drawable.shop_icon);
        drawable.setColorFilter(ContextCompat.getColor(this, R.color.white), PorterDuff.Mode.SRC_IN);
        shopBtn.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
        mRootView.setVisibility(View.INVISIBLE);
        mBottomBar.setVisibility(View.INVISIBLE);
        mFunctionBtn.setOnClickListener(this);
        mPlayIntroductionBtn.setOnClickListener(this);
        shopBtn.setOnClickListener(this);
        this.findViewById(R.id.share_btn).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if(mGroup==null)
            return;
        int id=v.getId();
        if(id==R.id.group_function_btn){
            switch (mGroup.getStatus()){
                case 0:
                    if(mIsJoin){
                        Wechat wechat= (Wechat) ShareSDK.getPlatform(Wechat.NAME);
                        if(wechat.isClientValid()){
                            Goods goods=mGroup.getOrder().getOrder_goods();
                            if(goods==null)
                                return;
                            Platform.ShareParams params=new Platform.ShareParams();
                            params.setShareType(Platform.SHARE_WEBPAGE);
                            params.setUrl(CommonTool.SHARE_GROUP_URL + mGroup.getGroup_order_id());
                            params.setImageUrl(goods.getImage_url());
                            params.setText(goods.getGoods_desc());
                            params.setTitle("我买了“"+goods.getGoods_name()+"”,再慢就被人抢走了!");
                            wechat.share(params);
                        }else {
                            ToastTool.showToast(getResources().getString(R.string.wechat_not_support_msg));
                        }
                    }else{
                        if(mIsLogin){
                            Bundle bundle=new Bundle();
                            if(mGroup.getOrder()!=null)
                                bundle.putSerializable("goods", mGroup.getOrder().getOrder_goods());
                            bundle.putString("groupId", mGroup.getGroup_order_id());
                            bundle.putInt("groupBuy", 1);
                            Intent intent=new Intent(this,CreateOrderActivity.class);
                            intent.putExtras(bundle);
                            startActivityForResult(intent, 0);
                        }else {
                            ToastTool.showToast("登录后方可参团");
                        }
                    }
                    break;
                case 1:
                case 2:
                    if(mIsLogin){
                        Bundle bundle=new Bundle();
                        if(mGroup.getOrder()!=null)
                            bundle.putSerializable("goods", mGroup.getOrder().getOrder_goods());
                        bundle.putInt("groupBuy", 1);
                        Intent intent=new Intent(this,CreateOrderActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }else {
                        ToastTool.showToast("登录后方可开团");
                    }
                    break;
            }
        }else if(id==R.id.play_introduction_btn) {
            startActivity(new Intent(this,PlayIntroductionActivity.class));
        }else if(id==R.id.shop_btn){
            if(mGroup.getOrder()!=null && mGroup.getOrder().getOrder_goods()!=null){
                String shopId=mGroup.getOrder().getOrder_goods().getShop_id();
                if(TextUtils.equals("0",shopId)){
                    ToastTool.showToast("暂无店铺");
                }else {
                    Intent intent = new Intent(this, ShopDetailActivity.class);
                    intent.putExtra("id",shopId);
                    startActivity(intent);
                }
            }
        }else if(id==R.id.share_btn){
            Goods goods=mGroup.getOrder().getOrder_goods();
            if(goods==null)
                return;
            ShareDialog shareDialog=ShareDialog.newDialog(goods.getImage_url(),"我买了“"+goods.getGoods_name()+"”,再慢就被人抢走了!",goods.getGoods_desc()
                    ,CommonTool.SHARE_GROUP_URL+mGroup.getGroup_order_id());
            shareDialog.show(getSupportFragmentManager(),"share");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode!=RESULT_OK)
            return;
        if(requestCode==0){
            requestGroupDetail();
        }
    }

    private void requestGroupDetail(){
        StringBuilder builder=new StringBuilder("?g=Api&m=Goods&a=group_orders");
        //builder.append("&token="+getMainApplication().getToken());
        builder.append("&id="+getIntent().getStringExtra("id"));
        HttpTool.get(this, builder.toString(), new JsonHttpHandler<Group>() {
            @Override
            public Group parseData(JSONObject object) throws Throwable {
                Group group=JSON.parseObject(object.getString("group_order"), Group.class);
                mIsJoin=false;

//                for(int i=0;i<10;i++)
//                    group.getUsers().add(new User());
                if(group!=null && mIsLogin) {
                    int userCount = group.getUsers() == null ? 0 : group.getUsers().size();
                    for (int i = 0; i < userCount; i++) {
                        if (TextUtils.equals(getMainApplication().getAccount().getUser_sn(), group.getUsers().get(i).getUser_id())) {
                            mIsJoin = true;
                            break;
                        }
                    }
                }
                return group;
            }

            @Override
            public void onStart() {
                super.onStart();
                mLoad.startLoad();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mLoad.finishLoad();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, Group errorResponse) {
                super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
                if(mGroup==null)
                    finish();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Group response) {
                if (response != null) {
                    mGroup = response;
                    mGroupIdText.setText("团ID " + response.getGroup_order_id());
                    mTimeText.updateLastTime(mGroup.getCurrent_time(),mGroup.getExpire_time());
                    Order order = response.getOrder();
                    if (order != null) {
                        Goods goods = order.getOrder_goods();
                        if (goods != null) {
                            Glide.with(GroupDetailActivity.this).load(goods.getImage_url())
                                    .centerCrop().into(mGoodsImage);
//                            initGoodsPrice(goods);
                            mGoodsPriceText.setText(CommonTool.getPriceFormatString(GroupDetailActivity.this,goods,1));
                            mGoodsNameText.setText(goods.getGoods_name());
                        }
                    }
                    if (response.getUsers() != null && response.getUsers().size() > 0) {
                        User user = response.getUsers().get(0);
                        Glide.with(GroupDetailActivity.this).load(user.getAvatar())
                                .transform(new CircleTransformation(GroupDetailActivity.this)).into(mLeaderHeadImage);
                        mLeaderNameText.setText("团长: " + user.getNickname());
                    }
                    mAdapter=new GroupUserAdapter(GroupDetailActivity.this);
                    mRecycler.setAdapter(mAdapter);
                    switch (mGroup.getStatus()){
                        case 0:
                            mStatusImage.setVisibility(View.INVISIBLE);
                            mPlayIntroductionBtn.setImageResource(mIsJoin ? R.drawable.pin_play_step_two_image : R.drawable.pin_play_step_one_image);
                            mFunctionBtn.setText(mIsJoin?"邀请好友":"我要参团");
                            break;
                        case 1:
                            mStatusImage.setVisibility(View.VISIBLE);
                            startStatusImageAnimator();
                            mStatusImage.setImageResource(R.drawable.group_success_image);
                            mPlayIntroductionBtn.setImageResource(R.drawable.pin_play_step_three_image);
                            mFunctionBtn.setText("我要开团");
                            break;
                        case 2:
                            mStatusImage.setVisibility(View.VISIBLE);
                            startStatusImageAnimator();
                            mStatusImage.setImageResource(R.drawable.group_fail_image);
                            mPlayIntroductionBtn.setImageResource(R.drawable.pin_play_step_one_image);
                            mFunctionBtn.setText("我要开团");
                            break;
                    }
                    mRootView.setVisibility(View.VISIBLE);
                    mBottomBar.setVisibility(View.VISIBLE);
                }
            }
        });
    }
    private void startStatusImageAnimator(){
        AnimatorSet set=new AnimatorSet();
        set.playTogether(ObjectAnimator.ofFloat(mStatusImage, "scaleX", 6f, 1f),
                ObjectAnimator.ofFloat(mStatusImage,"scaleY",6f,1f),
                ObjectAnimator.ofFloat(mStatusImage,"alpha",0f,1f));
        set.setDuration(800);
        set.setInterpolator(new DecelerateInterpolator());
        set.start();
    }
    private class UserItemDecoration extends RecyclerView.ItemDecoration{
        private float mDashWidth;
        private float mDashGap;
        private Paint mDashPaint;
        //private Path mPath;
        public UserItemDecoration() {
            mDashWidth=getResources().getDisplayMetrics().density*6;
            mDashGap=getResources().getDisplayMetrics().density*3;
            mDashPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
            mDashPaint.setColor(ContextCompat.getColor(GroupDetailActivity.this, R.color.red));
            mDashPaint.setStyle(Paint.Style.STROKE);
            mDashPaint.setStrokeWidth(getResources().getDisplayMetrics().density*3);
            DashPathEffect effect=new DashPathEffect(new float[]{mDashWidth,mDashGap},0);
            mDashPaint.setPathEffect(effect);
            //mPath=new Path();
        }

        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            int childCount=parent.getChildCount();
            for(int i=0;i<childCount;i++){
                ViewGroup childParent= (ViewGroup) parent.getChildAt(i);
                if(parent.getChildAdapterPosition(childParent)==parent.getAdapter().getItemCount()-1) {
                    continue;
                }
                View headImage=childParent.findViewById(R.id.group_user_head_image);
                float x=headImage.getLeft()+headImage.getWidth()/2;
                Path path=new Path();
                path.moveTo(x,childParent.getTop());
                path.lineTo(x, childParent.getBottom());
                c.drawPath(path,mDashPaint);
            }
        }
    }
    public class GroupUserAdapter extends BaseRecyclerAdapter<User> {
        int mLostUserNum;
        public GroupUserAdapter(Context context) {
            super(context, mGroup.getUsers());
            mLostUserNum = 0;
            if (mGroup.getOrder() != null && mGroup.getOrder().getOrder_goods() != null) {
                mLostUserNum = mGroup.getOrder().getOrder_goods().getGroup_number() - getListSize();
            }
        }

        @Override
        public int getItemCount() {
            if (getListSize() == 0)
                return super.getItemCount();
            return super.getItemCount() + 1;
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.group_user_item, parent, false);
            return new UserHolder(view);
        }

        @Override
        public void onBindHolder(RecyclerView.ViewHolder holder, int position) {
            UserHolder userHolder = (UserHolder) holder;
            if (position == 1) {
                userHolder.floorText.setVisibility(View.INVISIBLE);
                userHolder.dataText.setText("还差" + mLostUserNum + "人,让小伙伴们都来组团吧!");
                userHolder.dataText.setTextColor(ContextCompat.getColor(getContext(), R.color.dark_blue));
                userHolder.userHeadImage.setImageResource(R.drawable.group_user_default_image);
            } else {
                userHolder.dataText.setTextColor(ContextCompat.getColor(getContext(), R.color.dark));
                userHolder.floorText.setVisibility(View.VISIBLE);

                if (position > 0)
                    position = getListSize() - position + 1;
                User user = getList().get(position);
                userHolder.floorText.setText(position == 0 ? "团长" : position + "楼");
                SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String joinTime = format.format(new Date(user.getJoin_time() * 1000));
                String nickname=user.getNickname();
                if(mIsLogin && TextUtils.equals(user.getUser_id(),getMainApplication().getAccount().getUser_sn())) {
                    nickname="我";
                }
                userHolder.dataText.setText(joinTime + "\n" + nickname + (position == 0 ? " 发起拼团" : " 成功加入"));
                Glide.with(getContext()).load(user.getAvatar()).placeholder(R.drawable.group_user_default_image)
                        .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                        .skipMemoryCache(true)
                        .error(R.drawable.group_user_default_image)
                        .transform(new CircleTransformation(getContext(), R.dimen.group_user_list_head_border,
                                (position == 0 ? R.color.red : R.color.white))).into(userHolder.userHeadImage);
            }
        }

        private class UserHolder extends RecyclerView.ViewHolder {
            ImageView userHeadImage;
            TextView floorText, dataText;

            public UserHolder(View itemView) {
                super(itemView);
                userHeadImage = (ImageView) itemView.findViewById(R.id.group_user_head_image);
                floorText = (TextView) itemView.findViewById(R.id.group_user_floor_text);
                dataText = (TextView) itemView.findViewById(R.id.user_data_text);
            }
        }
    }
//    private void initGoodsPrice(Goods goods){
//        SpannableStringBuilder builder=new SpannableStringBuilder();
//        DecimalFormat format=new DecimalFormat("0.##");
//        SpannableString spannableString=SpannableString.valueOf(goods.getGroup_number()+"人拼团价: ");
//        spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.red)), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        builder.append(spannableString);
//        SpannableString priceString=SpannableString.valueOf(format.format(goods.getGroup_price()));
//        SpannableString unitString=SpannableString.valueOf("￥");
//        unitString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.red)), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        builder.append(unitString);
//        priceString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(this, R.color.red)), 0, priceString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        priceString.setSpan(new AbsoluteSizeSpan(18, true), 0, priceString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        builder.append(priceString);
//        builder.append(" ");
//        SpannableString marketPriceString=SpannableString.valueOf("￥"+format.format(goods.getMarket_price()));
//        marketPriceString.setSpan(new StrikethroughSpan(), 0, marketPriceString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        marketPriceString.setSpan(new AbsoluteSizeSpan(12, true), 0, marketPriceString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        builder.append(marketPriceString);
//        mGoodsPriceText.setText(builder);
//    }
}
